<?php
class IndexAction extends CoreAction {
	
	var $postlimit = 40; //多少个回复算一页
	
	function index() {	
		$index['hot'] = $this->topic->field('id,board,title')->order('replycount DESC')->limit(6)->findall();
		$index['affiche'] = $this->topic->field('id,board,title')->where('top>0')->order('top DESC')->limit(6)->findall();
		$index['totalCount'] = D('Board')->getTotalCount();
		$index['todayCount'] = D('Board')->getTodayCount();
		$this->assign($index);
		$this->site['title']	=	L('base_title');
		$this->setTitle();
		$this->display();
	}
	
	function all(){
		$map['isdel'] = 0;
 		//精华贴
		if($_GET['dist']=='1'){
			$map['dist'] = 1;
		}
		$list['isdist'] = intval( $_GET['dist'] );

		//获取贴子列表，依照分类列表
		$order0 = ( in_array($_REQUEST['order0'],array('rTime','cTime','viewcount','replycount')) )?$_REQUEST['order0']:'rTime';
		$order1 = ( $_REQUEST['order1']=='asc' ) ? 'asc' : 'desc';
		$strOrder	=	$order0.' '.$order1;
		$neworder1	=	( $order1=='desc' ) ? 'asc' : 'desc';
		$this->assign('order0',$order0);
		$this->assign('order1',$neworder1);

		$list['topic']  = $this->topic->where($map)->field('*')->order($strOrder)->findpage(40);
		$this->assign( $list );
		$this->setTitle ('全部帖子 - 论坛');
		$this->display();
	}

	
	//订阅
	public function attention() {
		$attentionData = $this->_getAttentionData ();
		$count = count ( $attentionData );
		$cate = model ( 'Xcate' )->getTree ( 'bbs', '0' );
		$json = json_encode ( $cate );
		
		$firstCate = sprintf ( '["%s","%s"]', $cate [0] ['a'], $cate [0] ['d'] [0] ['a'] );
		$this->assign ( 'firstCate', $firstCate );
		$this->assign ( 'attentionCount', $count );
		$this->assign ( 'jeson', $json );
		$this->assign ( 'attentionData', $attentionData );
		$this->display ();
	}
	
	protected function _getAttentionData($add = true) {
		//获取关注数据
		$attentionData = service ( 'Follow' )->getFollowData ( $uid = $this->mid, $type = 'bbs' );
		
		if (! empty ( $attentionData )) {
			$tagDao = model ( 'Xtag' );
			foreach ( $attentionData as &$value ) {
				$cid = $value;
				$value = array ();
				if (! $add) {
					$title = explode ( ',', $tagDao->getTagName ( $cid ) );
					$value ['title'] = array_pop ( $title );
				} else {
					$value ['title'] = str_replace ( ',', ' > ', $tagDao->getTagName ( $cid ) );
				}
				$value ['cid'] = $cid;
			}
		}
		return $attentionData;
	}	
		
	//发表新主题
	function post(){
		$forum['class'] = trim( $_GET['class'] );
		$this->getTopNav( $forum['class'] );  //获取导航;
		$forum['topnav'] = $this->_topnav;
		unset( $forum['topnav'][0] );
		$this->setTitle ('发表新主题 - 论坛');
		
		foreach ($forum['topnav'] as $key=>$value){
			preg_match("/(<a.*?>)(.*?)(<\/a>)/",$value,$result);
			$defaulnave[] = $result[2];
		}
		$forum['defaultCategory'] = $defaulnave;
		$forum['tclasslist'] = D('Board')->gettClass( $forum['class'] );
		$this->assign($forum);
		$this->display();
	}
	
	//抄送
	function transcribe(){
		$uids   = trim($_GET['uids']);
		$uids   = strpos($uids,',') === false ? $uids:explode(',',$uids);
    	$map['uid'] = array('in',$uids);
    	$user = D('User')->where($map)->field('fullname,uid,uname')->findAll();
    	$this->assign('userList',$user);
    	$this->assign('userId',$uids);
    	$this->display();
	}
	
	function detail(){
		$id = intval( $_GET['id'] );
		$forum['limit']  = $this->postlimit;
		$forum['topic']  = $this->topic->getTopic($id);
		if( !$forum['topic'] ) $this->error(L('1001'));
				
		$this->class = $forum['topic']['board'];
		$this->boardPurview();   //载入权限控制器
		//dump($this->_Core );
		$map['tid'] = $forum['topic']['id'];
		if($_GET['auther']==1) $map['uid'] =  $forum['topic']['uid'];
		$forum['isReadAuther'] = intval( $_GET['auther'] );
		$this->getTopNav( $this->class );  //获取导航;
		$forum['list']   = $this->post->where($map)->order('id ASC')->findPage( $forum['limit'] );
		
		//获取用户等级、积分、经验、发贴、回复
//		$arrUids = getSubByKey( $forum['list']['data'] , 'uid' );
//		$uidsMap['uid'] = array('in',$arrUids);
//		$arrUids = M('space')->where($uidsMap)->field('uid,credit_score,credit_exp')->findAll();
		$highighter = service('Highlighter'); //高亮显示
		
		foreach ($forum['list']['data'] as $key=>$value){
			$forum['list']['data'][$key]['attach']  = unserialize( $forum['list']['data'][$key]['attach'] );
			$forum['list']['data'][$key]['content'] = $highighter->syntax( $forum['list']['data'][$key]['content'] );
		}
		
//		//记录用户浏览时间
		$array = ( $_SESSION['visit_bbs_topic'] )?$_SESSION['visit_bbs_topic']:array();
		if(!in_array( $forum['topic']['id'], $array )){
			$this->topic->setInc('viewcount','id='.$forum['topic']['id']);
			array_push($array,$forum['topic']['id']);
			$_SESSION['visit_bbs_topic'] =  $array ;
		}	
		$forum['currentUrl'] = U('bbs/Index/detail',array('id'=>$id));
		//$forum['sharedata']['title']  = 'board:'.implode( " >> ", $this->getTopNav( $this->class , true ) );
		$this->assign($forum);
		$this->site['title']	=	$forum['topic']['title'].' - '.L('base_forum');
		$this->setTitle();			
		$this->display();
	}
	
	//跳转至主题某页某个位置
	function gopost(){
		$intId  = intval( $_GET['id'] );
		$intPid = intval( $_GET['pid'] );
		
		$page = $this->post->where("tid=$intId AND id < $intPid")->count();
		$page = intval( $page/($this->postlimit) +1 );
		redirect( U('bbs/Index/detail',array('id'=>$intId,'p'=>$page))."#p".$intPid );
	}
	
	function reply(){
		$intId = intval( $_GET['id'] );
		
		$data['postInfo'] = $this->post->getPostInfo( $intId );
		
		if($_GET['fast']){
			$data['fastreply'] = true;
		}
		if($_GET['quote']){
			$data['quoteContent'] = $data['postInfo']['content'];
		}
		
		$data['floor'] = $this->post->where('tid='.$data['postInfo']['tid'].' AND id<='.$intId)->count();
		$this->assign($data);
		$this->display();
	}
	
	function edit(){
		$intId             = intval( $_GET['pid'] );	
		$data['postInfo'] = $this->post->getPostInfo( $intId );
		/** 权限控制  **/
		$this->class = $data['postInfo']['board'];
		$this->boardPurview();   //载入权限控制
		if(!$this->_Core['isAdmin'] && $data['postInfo']['uid']!=$this->mid ){
			$this->error( L('error_no_purview') );
		}
		/** 权限控制 **/
		
		$data['tclasslist'] = D('Board')->gettClass( $data['postInfo']['board'] );

		$this->getTopNav( $data['postInfo']['board'] );  //获取导航;
		$this->assign( $data );
		$this->display();
	}
	
	function forumlist(){
		$this->class = trim( $_GET['class'] );
		$this->boardPurview();  //加载权限控制器
		
		$classInfo = model('Xcate')->getTree('bbs',$this->class) ;

		$list['class'] = $this->class;
		$list['classInfo'] = $classInfo[0];
		foreach (explode( ',',$list['classInfo']['m'] ) as $value){
			if($value) $manages[] = $value;
		}
		
		$list['classInfo']['m'] = $manages;
		
		$this->getTopNav( $this->class );  //获取导航
		$category = explode(',',$this->class);
			
		$list['tagid'] = end( $category );
		
		if( count($category) ==1 ){
			
			$child	=	array();
			getChildTagId( array( $list['classInfo'] ),$child);

			$map = "tagid IN (".implode(',',$child).")";
		}else{
			$map = "tagid=".end( $category );
		}
		
		$map .= " AND isdel=0";
		
		$list['isdist']  = intval($_GET['dist']);
		
		if( $list['isdist'] ){
			$map.= " AND dist=".$list['isdist'];
		}else{
			$map.=" AND top=0";
			$list['tclasslist'] = D('Board')->gettClass( $this->class );
		}
		//版块下专题分类
		$list['tclass']     = intval($_GET['tclass']);
		if( $list['tclass'] ) $map.= " AND tclass=".intval( $_GET['tclass'] );		

		//dump($list['top']);
		//echo $map;

		//获取贴子列表，依照分类列表
		$order0 = ( in_array($_REQUEST['order0'],array('rTime','cTime','viewcount','replycount')) )?$_REQUEST['order0']:'rTime';
		$order1 = ( $_REQUEST['order1']=='asc' ) ? 'asc' : 'desc';
		$strOrder	=	$order0.' '.$order1;
		$neworder1	=	( $order1=='desc' ) ? 'asc' : 'desc';
		$this->assign('order0',$order0);
		$this->assign('order1',$neworder1);

		$list['topic']  = $this->topic->where($map)->field('*')->order($strOrder)->findpage(40);
		if( $list['topic']['nowPage']==1 && $list['isdist']==0){
			$list['top']    = $this->topic->where('isdel=0 AND ( top=2 OR (tagid='.end($category).' AND top=1) )')->order('top DESC')->findall();
		}
		
		$list['totalCount'] = D('Board')->getTotalCount();
		$list['todayCount'] = D('Board')->getTodayCount();
		$this->assign( $list );
		
		$this->site['title']	=	$list['classInfo']['t'].' - '.L('base_forum');
		$this->setTitle();		
		$this->display();
	}
	
	public function selectCategory(){
		$cate = model('Xcate')->getTree('bbs','0');
		$json = json_encode($cate);
		$this->assign('class',$_GET['class']);
		$this->assign('json',$json);
		$this->display();
	}
	

	function getCategory(){
		$list = D('Board')->gettClass( intval($_REQUEST['tagid']) );
		exit(json_encode( $list ));
	}
	
	//digg
	public function userDig(){
		$options = array( 'id'=>$_POST['blogId'],'uid'=>$this->mid,'type'=>'bbs',"key"=>"dig",'lefttime'=>86400);
		$digResult = X('Browse',$options);
		$digResult = $digResult->run();
		switch($digResult){
			case 1:
				//dig成功
				$this->topic->setInc( 'dig','id='.intval($_POST['blogId']) );
				echo 1;
				break;
			case 0:
				//已经dig过了
				echo L('have_digged');
				break;
			default:
				//超时，将数据统计写入数据库
				$this->topic->setInc( 'dig','id='.intval($_POST['blogId']) );
				echo 1;
				break;
		}
	}
    

	/**
	 * 论坛的RSS输出
	 * depend: formatArray() / getChildTagId()
	 */
	public function generateRss() {
		$item    = array();
		$items   = array();
		$channel = array();

		//1, 获取数据
		$map   = array();
		$limit = 20;
		$order = 'cTime DESC';

		//板块中的帖子【仅支持单个板块】
		if(!empty($_GET['cid'])) {
			$class = trim( $_GET['cid'] );
			$classInfo = model('Xcate')->getTree('bbs',$class) ;
			$list['class'] = $class;
			$list['classInfo'] = $classInfo[0];
			foreach (explode( ',',$list['classInfo']['m'] ) as $value){
				if($value) $manages[] = $value;
			}
			
			$list['classInfo']['m'] = $manages;
			
			$category = explode(',',$class);
				
			$list['tagid'] = end( $category );
			
			if( count($category) ==1 ){
				
				$child	=	array();
				getChildTagId( array( $list['classInfo'] ),$child);

				$map = "tagid IN (".implode(',',$child).")";
			}else{
				$map = "tagid=".end( $category );
			}
			
			$map .= " AND isdel=0";
			
			$list['isdist']  = intval($_GET['dist']);
			
			if( $list['isdist'] ){
				$map.= " AND dist=".$list['isdist'];
			}else{
				$map.=" AND top=0";
				$list['tclasslist'] = D('Board')->gettClass( $class );
			}
			//版块下专题分类
			$list['tclass']     = intval($_GET['tclass']);
			if( $list['tclass'] ) $map.= " AND tclass=".intval( $_GET['tclass'] );

		}else {
			
			$map['isdel'] = 0;
		
		}

		$field = 'id,uid,title,cTime';
		$list  = M('bbs_topic')->where($map)->field($field)->order($order)->limit($limit)->findAll();

		//帖子的内容
		$content = array();
		$ids = formatArray($list, 'id');
		unset($map);
		$map['tid']     = array('in', $ids);
		$map['istopic'] = '1';
		$res = M('bbs_post')->where($map)->field('tid,content')->limit($limit)->findAll();
		foreach($res as $v) {
			$content[$v['tid']] = $v['content'];
		}

		//作者姓名
		$uids = formatArray($list, 'uid');
		unset($map);
		$map['uid'] = array('in', $uids);
		$res = M('user')->where($map)->field('uid,fullname')->limit(count($uids))->findAll();
		foreach($res as $v) {
			$author[$v['uid']] = $v['fullname'];
		}


		//2, 组装items
	    foreach($list as $k => $v) {
    	    $item = array(
    	        'title'         => $v['title'],
    	        'link'          => U('bbs/Index/detail',array('id'=>$v['id'])),
    	        'description'   => getShort(t($content[$v['id']]), 200), //输出200字的摘要
    	        'author'        => $author[$v['uid']],
    	        'guid'          => 'bbs_' . $v['id'],
    	        'pubDate'       => $v['cTime'],
    	    );
    	    
    	    $items[] = $item;
    	}

		//3, 组装channel
	    $channel = array(
	        'title'         => L('rss_title'),
	        'link'          => U('bbs/Index/index'),
	        'description'   => L('rss_description'),
	        //'category'      => '分类1/分类2', //TODO: 分情况
	        'copyright'     => '版权所有，违法必究',
	        'language'      => 'zh-cn',
	        'lastBuildDate' => time(),
	        'pubDate'       => time(),
	        'image'         => SITE_URL.'/public/themes/blue/images/3MS_logo.gif',
	        'webMaster'     => 'desheng.young@gmail.com',
	        'items'         => $items,
	    );

		//4, 输出
		$rss = service('RssGenerate')->generateRssXml($channel);
		header('Content-Type:text/xml;charset=utf-8');
		echo $rss;
	}

}
?>